package com.ts.api.module.api.convert.core.http.client;

import com.gitee.apanlh.exp.HttpConnectionException;
import com.gitee.apanlh.util.encode.StrEncodeUtils;
import com.gitee.apanlh.util.net.http.HttpClientBuilder;
import com.gitee.apanlh.util.net.http.HttpResponse;
import com.gitee.apanlh.util.valid.ValidParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 *  API请求HTTP客户端
 *
 *  @author Pan
 */
@Component
public class ApiHttpExecutor {

    @Autowired
    private ApiHttpRequestConfigure apiHttpRequestConfigure;

    /**
     *  发送HTTP请求
     *
     *  @param  httpMessage     http消息实体
     */
    public void execute(ApiHttpMessage httpMessage) {
        try {
            //  装配请求参数
            HttpClientBuilder httpClientBuilder = apiHttpRequestConfigure.clientConfigure(httpMessage);

            //  发送请求
            HttpResponse httpResp = httpClientBuilder.build();
            Object sendBody = httpClientBuilder.getRequest().getBody().getRequestBody();
            httpMessage.setRequestBody(sendBody);

            httpMessage.setRespCode(httpResp.getStatus().getCode());
            //  是否http请求错误
            if (httpResp.isError()) {
                httpMessage.setHasSuc(false);
                httpMessage.setErrorMsg(httpResp.getErrorMsg());
                return ;
            }

            //  是否响应体为空
            String responseBody = httpResp.getStr();
            if (ValidParam.isEmpty(responseBody)) {
                httpMessage.setHasSuc(false);
                httpMessage.setErrorMsg("响应消息体返回空");
                return ;
            }

            //  unicode转换
            if (responseBody.indexOf('\\') != -1 && responseBody.indexOf('u') != -1) {
                responseBody = StrEncodeUtils.unicodeDecode(responseBody);
            }

            httpMessage.setResponseBody(responseBody);
        } catch (HttpConnectionException httpConnectionException) {
            httpMessage.setHasReqTimeout(true);
            httpMessage.setHasSuc(false);
        } catch (Exception e) {
            httpMessage.setHasSuc(false);
            httpMessage.setExceptionInfo(e);
        }
    }
}
